import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/data_base/data_base.dart';
import 'package:flutter_bsbdj/pagers/music/music_channel_gg_detail.dart';
import 'package:flutter_bsbdj/pagers/music/music_channel_list.dart';
import 'package:flutter_bsbdj/pagers/music/music_channel_man_detail.dart';
import 'package:flutter_bsbdj/pagers/music/music_search.dart';
import 'package:flutter_bsbdj/bean/music_radio.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter_bsbdj/utils/widget_views.dart';
import 'package:flutter_bsbdj/bean/music_rank.dart';
import 'package:flutter_bsbdj/pagers/music/music_suspension_window.dart';

class Music extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MusicWidget();
  }
}

class MusicWidget extends State<Music> {
  List<MusicRadio> _radios;
  List<RankType> _rankTypes;
  double _marginBottom = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMusicRadio();
    _changMarginBottom();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("音乐"),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => MusicSearch()));
            },
          ),
        ],
      ),
      body: Container(
        margin: EdgeInsets.only(bottom: _marginBottom),
        child: ListView(
          children: <Widget>[
            Container(
              child: Column(
                children: _musicChannel(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //频道item
  List<Widget> _musicChannel() {
    List<Widget> wids = [];
    if (_radios == null) {
      return wids;
    }
    for (var channel in _radios) {
      wids.add(_musicRadioItem(channel));
    }
    if (_rankTypes != null) {
      for (var type in _rankTypes) {
        wids.add(_rankItem(type));
      }
    }
    return wids;
  }

  //音乐电台的item
  Widget _musicRadioItem(MusicRadio musicRadio) {
    if (musicRadio.channellist == null) {
      return Container();
    }
    return Container(
      height: 160,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            height: 40,
            padding: EdgeInsets.only(left: 5),
            child: Row(
              children: <Widget>[
                Text(musicRadio.title),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: IconButton(
                        icon: Icon(
                          Icons.more_vert,
                          color: Colors.blueAccent,
                          size: 20,
                        ),
                        onPressed: () {
                          //查看更多电台
                          Navigator.of(context)
                              .push(MaterialPageRoute(
                                  builder: (context) => ChannelList(
                                        musicRadio.channellist,
                                        musicRadio.cid,
                                        typeName: musicRadio.title,
                                      )))
                              .then((va) {
                            _changMarginBottom();
                          });
                        }),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Container(
              height: 110,
              child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: musicRadio.channellist.length >= 4
                      ? 4
                      : musicRadio.channellist.length,
                  itemBuilder: (content, index) {
                    return _audioItem(
                        musicRadio.channellist[index], musicRadio.cid);
                  }),
            ),
          ),
          Container(
            height: 1,
            color: Colors.black54,
          )
        ],
      ),
    );
  }

  //音乐电台分类
  //item's item
  Widget _audioItem(RadioItem item, int cid) {
    return GestureDetector(
      child: Column(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width / 4,
            padding: EdgeInsets.all(5),
            child: CachedNetworkImage(
              imageUrl: cid == 1 ? item.thumb : item.avatar,
              placeholder: (context, str) {
                return Image.asset("images/ic_loading.gif");
              },
              errorWidget: (context, str, object) {
                return Image.asset("images/error.png");
              },
            ),
          ),
          Text(
            item.name,
            style: TextStyle(fontSize: 12),
          ),
        ],
      ),
      onTap: () {
        if (cid == 1) {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (context) =>
                      ChannelGGDetail(item.name, item.ch_name)))
              .then((va) {
            _changMarginBottom();
          });
        } else {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (context) => ChannelManDetail(item.name, item.name)))
              .then((va) {
            _changMarginBottom();
          });
        }
      },
    );
  }

  //音乐排行榜
  Widget _rankItem(RankType type) {
    if (type.content == null || type.content.length == 0) {
      return Container();
    }
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(5),
//            height: 40,
            alignment: Alignment.centerLeft,
            child: Text(type.name),
          ),
          Container(
            margin: EdgeInsets.only(bottom: 20, left: 5, right: 5),
            child: GridView.builder(
                shrinkWrap: true,
                primary: false,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4, crossAxisSpacing: 5),
                itemCount: type.content.length,
                itemBuilder: (content, index) {
                  return WidgetViews.getInstance().cachedImageCover(
                      type.content[index].pic_big, function: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => ChannelManDetail(
                            type.content[index].title,
                            type.content[index].title)));
                  });
                }),
          ),
        ],
      ),
    );
  }

  void _getMusicRadio() async {
    var t = await Dio()
        .get("https://api.apiopen.top/musicBroadcasting")
        .then((value) {
      try {
        MusicRadioInfo info = MusicRadioInfo.fromJson(value.data);
        print(info);
        //只有当前widget还在 tree中才设置值
        if (mounted) {
          setState(() {
            _radios = info.result;
          });
        }
      } on DioError catch (e) {}
    });

    _getRank();
  }

  void _getRank() async {
    var t =
        await Dio().get("https://api.apiopen.top/musicRankings").then((value) {
      try {
        MusicRank info = MusicRank.fromJson(value.data);
        print(info);
        //只有当前widget还在 tree中才设置值
        if (mounted) {
          setState(() {
            _rankTypes = info.result;
          });
        }
      } on DioError catch (e) {}
    });
  }

  void _changMarginBottom() async {
    await Future.delayed(Duration(milliseconds: 400), () {
      setState(() {
        if (MusicWindowPlay.getInstance(context).musicIsPlaying()) {
          _marginBottom = 60;
          MusicWindowPlay.getInstance(context).isHeidden(false);
        } else {
          _marginBottom = 0;
        }
      });
    });
  }
}
